package com.kun.kunkunmall.auth.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.TypeReference;
import com.kun.common.utils.HttpUtils;
import com.kun.common.utils.R;
import com.kun.kunkunmall.auth.feign.MemberFeignService;
import com.kun.kunkunmall.auth.vo.GiteeUserVo;
import com.kun.common.vo.MemberRespVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理社交登录请求
 */
@Controller
public class OAuthu2Controller {

    @Autowired
    private MemberFeignService memberFeignService;

    @GetMapping("/gitee/success")
    public String gitee(@RequestParam("code") String code, HttpSession session) throws Exception {
        // 根据code换取access_token
        Map<String, String> map = new HashMap<>();
        map.put("client_id", "a2a0dbd6c297f985a9c83f75174f7d2c2e2cd2164f74b42e5ab24e300cdadc68");
        map.put("client_secret", "9d297a2abee8675a6d2c0f99995cf6f0913047d0042e87c2c067e3fe2db46c67");
        map.put("redirect_uri", "http://auth.kunkunmall.com/gitee/success");
        map.put("grant_type", "authorization_code");
        map.put("code", code);
        HttpResponse httpResponse = HttpUtils.doPost("https://gitee.com/", "/oauth/token", "post", new HashMap<>(), map, new HashMap<>());
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            // 获取到了access_token
            // 登录成功跳回首页，将响应信息封装为实体类
            String jsonStr = EntityUtils.toString(httpResponse.getEntity());
            GiteeUserVo giteeUserVo = JSONUtil.toBean(jsonStr, GiteeUserVo.class);
            // 利用access_token去查询用户的id（用户的唯一标示）
            Map<String, String> giteeUserMap = new HashMap<String, String>();
            giteeUserMap.put("access_token", giteeUserVo.getAccess_token());
            HttpResponse response = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", new HashMap<>(), giteeUserMap);
            if (response.getStatusLine().getStatusCode() == 200) {
                String giteeUserStr = EntityUtils.toString(response.getEntity());
                GiteeUserVo giteeUserVoTemp = JSONUtil.toBean(giteeUserStr, GiteeUserVo.class);
                BeanUtil.copyProperties(giteeUserVoTemp,giteeUserVo, CopyOptions.create().ignoreNullValue().setIgnoreProperties("expires_in","created_at"));

                // 知道了是哪个社交用户
                // （1）当前用户是第一次登录我们网站，就自动注册进来（为当前社交用户生成一个会员信息账号）
                R r = memberFeignService.oauth2Login(giteeUserVo);
                if (r.getCode() == 0) {
                    // 远程调用成功
                    MemberRespVo memberRespVo = r.getData("data", new TypeReference<MemberRespVo>() {
                    });
                    System.out.println("登录成功，用户信息："+memberRespVo);
                    session.setAttribute("loginUser",memberRespVo);
                    return "redirect:http://kunkunmall.com";
                }else {
                    // 远程调用失败
                    return "redirect://http://auth.kunkunmall.com/login.html";
                }
            }else {
                return "redirect://http://auth.kunkunmall.com/login.htm";
            }

        } else {
            return "redirect://http://auth.kunkunmall.com/login.html";
        }

    }
}

